<template>
  <div class="network-tab">

    <div class='mb10 flex'>
      <!-- <FieldInfo :list="firstInfoList" :data="avgRespTimeData" mode='card'></FieldInfo> -->
      <div v-for="item in firstInfoList" class="card" :key="item.key" :style="item.style || {}">
        <div class="card-title" :title="item.title">{{ item.title }}:</div>
        <div class="card-value">
          <span>{{ formatUnit(avgRespTimeData[item.dataIndex], item.unit) }}</span>
          <RateInfo title='同比' :value="avgRespTimeData.requestTotalSameRatio" style="margin: 0 8px " />
          <RateInfo title='环比' :value="avgRespTimeData.requestTotalRingRatio" />
        </div>

      </div>
    </div>
    <div class='mb10 flex'>
      <!-- <FieldInfo :list="secondInfoList" :data="{ packetLoss, retransmit, SRTT, ...avgRespTimeData }" mode='card' /> -->
      <div v-for="(item, index) in secondInfoList" class="card" :key="item.key" :style="item.style || {}">
        <div class="card-title" :title="item.title">{{ item.title }}:</div>
        <div class="card-value">
          <template v-if="item.isCustom">

            <span>{{ formatUnit(secondFieldsData[item.dataIndex], 'count') }}</span>
            <RateInfo title='同比' :value="secondFieldsData.requestTotalSameRatio" style="margin: 0 8px " />
            <RateInfo title='环比' :value="secondFieldsData.requestTotalRingRatio" />
          </template>

          <span v-else>{{ secondFieldsData[item.dataIndex] ?? '--' }}</span>
        </div>

      </div>
    </div>
    <div>
      <ga-row :gutter="16">
        <ga-col :span="8">
          <ChartWithPicker title="请求量" :option="chartOptions.requestOption" :params="lineParams"
            @on-time-refresh="getRequestCountLine " @on-filter="() => emits('on-filter') " />
        </ga-col>
        <ga-col :span="8">
          <ChartWithPicker title="错误率" :option="chartOptions.errorOption" :params="lineParams"
            @on-time-refresh="getErrorLine " @on-filter="() => emits('on-filter') " />
        </ga-col>
        <ga-col :span="8">
          <ChartWithPicker title="错误率" :option="chartOptions.errorOption" :params="lineParams"
            @on-time-refresh="getErrorLine " @on-filter="() => emits('on-filter') " />
        </ga-col>
      </ga-row>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
// import FieldInfo from '@/components/FieldInfo'
import RateInfo from '@/components/RateInfo'
import ChartWithPicker from '@/components/ChartWithPicker'
import { formatUnit } from '@/utils/format';
import {
  queryRequestTotalLine, queryErrorLine, queryRespTimeLine, queryP95RespTimeLine, queryPacketLossLine, queryRetransmitLine,
  querySRTTLine, queryZeroWindowLine, querySessionCountLine, querySendPackageLine, queryReceiverPackageLine, getAvgRespTime,
  avgRespTimeByPod
} from '@/api/topoNodeDetail'
import { lineOptionHandle, netLineOptionHandle } from '../../service';
import { basiclineOption } from '@/utils/chartOption';
import { map, cloneDeep } from 'lodash'

defineOptions({
  name: 'NetworkTab'
})

const props = defineProps({
  node: {
    type: Object,
    default: () => ({})
  },
  queryTime: {
    type: Object,
    default: () => ({})
  },
  srcNodes: {
    type: Object,
    default: () => ([])
  },
  type: {
    type: String,
  }
})
const emits = defineEmits(['on-filter'])


const firstInfoList = [{
  title: '请求量',
  dataIndex: 'requestTotal',
  unit: 'count',

}, {
  title: '错误率',
  dataIndex: 'errorRatio',
  unit: '%',

}, {
  title: 'P95响应时间',
  dataIndex: 'p95ResponseTime',
  unit: 'ns',

}]
const secondInfoList = [
  {
    title: '平均响应时间',
    dataIndex: 'avgResponseTime',
    style: { flexGrow: 1.6 },
    isCustom: true,
    // render: (text, data) => h('template', [
    //   h('span', formatUnit(text, 'ns')),
    //   h(RateInfo, { title: '同比', value: data.avgResponseTimeSameRatio, style: 'margin: 0 8px' }),
    //   h(RateInfo, { title: '环比', value: data.avgResponseTimeRingRatio })
    // ])

  },
  {
    title: '重传数',
    dataIndex: 'retransmit',

  },
  {
    title: '丢包数',
    dataIndex: 'packetLoss',

  },
  {
    title: 'SRTT',
    dataIndex: 'SRTT',

  },
];

const avgRespTimeData = ref({})
const packetLoss = ref('')
const retransmit = ref('')
const SRTT = ref('')
const secondFieldsData = computed(() => {
  return {
    SRTT: formatUnit(SRTT.value, 'us'),
    retransmit: retransmit.value,
    packetLoss: packetLoss.value,
    ...avgRespTimeData.value
  }
})
const lineParams = ref()
const chartOptions = reactive({
  requestOption: basiclineOption,
  errorOption: basiclineOption,
  resTimeOption: basiclineOption,
  p95ResTimeOption: basiclineOption,
  packetLossOption: basiclineOption,
  retransmitOption: basiclineOption,
  zeroWindowOption: basiclineOption,
  sessionOption: basiclineOption,
  sendPackageOption: basiclineOption,
  receiverPackageOption: basiclineOption,
  srttOption: basiclineOption
})
const type = props.type
const getRequestCountLine = (params) => {
  queryRequestTotalLine(params, type).then(res => {
    console.log(res, 'res');

    if (res.code == 200) {
      const option = lineOptionHandle(res.data, 'rc');
      // setRequestOption(option);
      chartOptions.requestOption = option
    }
  });
}
const getErrorLine = (params) => {
  queryErrorLine(params, type).then(res => {
    if (res.code == 200) {
      const option = lineOptionHandle(res.data, 'error');

      chartOptions.errorOption = option
    }
  });
}
const getRespTimeLine = (params) => {
  queryRespTimeLine(params, type).then(res => {
    if (res.code == 200) {
      const option = lineOptionHandle(res.data, 'rt');
      chartOptions.resTimeOption = option
      // setRespTimeOption(option);
    }
  });
}
const getP95RespTimeLine = (params) => {
  queryP95RespTimeLine(params, type).then(res => {
    if (res.code == 200) {
      const option = lineOptionHandle(res.data, 'rt');
      chartOptions.p95ResTimeOption = option
      // setP95RespTimeOption(option);
    }
  });
}
const getPacketLossLine = (params) => {
  queryPacketLossLine(params, type).then(res => {
    const { lineChartVos, total } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], '丢包数', '');
    packetLoss.value = total
    chartOptions.packetLossOption = option
    // setPacketLoss(total);
    // setPacketLossOptions(option);
  })
}
const getRetransmitLine = (params) => {
  queryRetransmitLine(params, type).then(res => {
    const { lineChartVos, total } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], '重传数', '');
    retransmit.value = total
    chartOptions.retransmitOption = option
    // setRetransmit(total);
    // setRetransmitOptions(option);
  })
}
const getSRTTLine = (params) => {
  querySRTTLine(params, type).then(res => {
    const { lineChartVos, total } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], 'SRTT', 'us');
    SRTT.value = total;
    chartOptions.srttOption = option
    // setSRTT(total);
    // setSRTTOptions(option);
  })
}
// 0窗口
const getZeroWindowLine = (params) => {
  queryZeroWindowLine(params, type).then(res => {
    const { lineChartVos } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], '0窗口', '');
    chartOptions.zeroWindowOption = option
    // setZeroWindowOptions(option);
  })
}

// 活跃会话数
const getSessionCountLine = (params) => {
  querySessionCountLine(params, type).then(res => {
    const { lineChartVos } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], '活跃会话数', '');
    chartOptions.sessionOption = option
    // setSessionCountOptions(option);
  })
}

// 发包数
const getSendPackageLine = (params) => {
  querySendPackageLine(params, type).then(res => {
    const { lineChartVos } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], '发包数', '');
    chartOptions.sendPackageOption = option
    // setSendPackageOptions(option);
  })
}

// 收包数
const getReceiverPackageLine = (params) => {
  queryReceiverPackageLine(params, type).then(res => {
    const { lineChartVos } = res.data;
    const option = netLineOptionHandle(lineChartVos || [], '收包数', '');
    chartOptions.receiverPackageOption = option
    // setReceiverPackageOptions(option);
  })
}
const getLine = () => {
  // console.log(srcNodes, 'nodes',node);
  // const node = props.node
  const { from, to } = props.queryTime
  const { type, node, srcNodes } = props
  const baseParams = {
    dstMasterIp: node.masterIp,
    dstNamespace: node.namespace,
    dstWorkloadName: node.workloadName,
    dstWorkloadKind: node.workloadKind,
    from,
    to,
  }
  const params = type === 'workload' ? {
    ...baseParams,
    srcWorkloadList: map(srcNodes, node => {
      return {
        masterIp: node.masterIp,
        namespace: node.namespace,
        workloadKind: node.workloadKind,
        workloadName: node.workloadName,
      }
    })
  } : {
    ...baseParams,
    dstPodName: node.podName,
    srcPodList: map(srcNodes, ({ masterIp, namespace, workloadKind, workloadName, podName }) => {
      return {
        masterIp,
        namespace,
        workloadKind,
        workloadName,
        podName,
      }
    })
  }

  // setLineParams(params);
  lineParams.value = params
  getRequestCountLine(params);
  getErrorLine(params);
  getRespTimeLine(params);
  getP95RespTimeLine(params);
  getPacketLossLine(params);
  getRetransmitLine(params);
  getSRTTLine(params);
  getSessionCountLine(params);
  getAvgRespTimeData(params);
  // vm类型不去请求0窗口、发包数和收包数
  if (node.workloadKind !== 'vm') {
    getZeroWindowLine(params);
    getSendPackageLine(params);
    getReceiverPackageLine(params);
  }
}
// 平均响应时间同环比数据 补充了数据不止平均响应时间
const getAvgRespTimeData = (params) => {
  const req = type === 'pod' ? avgRespTimeByPod(params) : getAvgRespTime(params)
  req.then(res => {
    // const { avgResponseTime, avgResponseTimeRingRatio, avgResponseTimeSameRatio } = res.data.data || {};
    // setAvgRespTimeData(res.data || {})
    avgRespTimeData.value = res.data || {}
  })
}
const respTimeRefresh = (params) => {
  if (respSelectValue === 'p95') {
    getP95RespTimeLine(params);
  } else {
    getRespTimeLine(params);
  }
}
// console.log(props, 'props');

watch([() => props.node, () => props.queryTime], ([newNode, newTime]) => {
  // console.log(newNode, 'new node');

  if (newNode && newTime.from) {


    getLine();
  }
})
// onMounted(() => {
//   getLine();
// })
</script>

<style scoped lang="scss">
.network-tab {
  .card {
    background-color: rgba(34, 110, 231, 0.06);
    padding: 12px;
    border-radius: 4px;
    flex-basis: 0;
    flex-grow: 1;
    margin: 0 4px;
    overflow: hidden;

    .card-title {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .card-value {
      font-size: 18px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
    }

    &:first-child {
      margin-left: 0;
    }

    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
